angular.module('app.service', [])
    .service('ajax', function ($log, $http, $q) {
        return {
            call: function (params) {
                params["module"] = window.location.hash;
                if (!params.resource) {
                    console.debug('resource is null');
                    return;
                }
                var deferred = $q.defer();	// 声明延后执行，表示要去监控后面的执行
                $http({
//                    url: params.resource,
                	url: 'ajax',
                    method: 'POST',
                    headers: { 'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8" },
//                    data: params.fields
                    data: encodeURI("resource=" + params.resource + "&type=" + params.method + "&param=" + JSON.stringify(params))
                }).then(function successCallback(response) {
                    deferred.resolve(response.data);	// 声明执行成功，即http请求数据成功，可以返回数据了
                }, function errorCallback(response) {
                    deferred.reject(response);		// 声明执行失败，即服务器返回错误
                });
                return deferred.promise;	// 返回承诺，这里并不是最终数据，而是访问最终数据的API
            },
            // 快速请求 @GET
            get: function (resource, callback, errorCallback) {
                this.call(new Req.GET({
                    resource: resource
                })).then(callback, errorCallback);
            },
            // 快速请求 @POST
            post: function (resource, param, callback, errorCallback) {
                param = param || { data: {} };
                this.call(new Req.POST({
                    id: param.data.id || '',
                    fields: param.data || {},
                    datalist: param.datalist || [],
                    resource: resource
                })).then(callback, errorCallback);
            },
            // 快速请求 @PUT
            put: function (resource, param, callback, errorCallback) {
                param = param || { data: {} };
                this.call(new Req.PUT({
                    id: param.data.id || '',
                    fields: param.data || {},
                    datalist: param.datalist || [],
                    resource: resource
                })).then(callback, errorCallback);
            },
            del: function (resource, callback, errorCallback) {
                this.call(new Req.POST({
                    resource: resource
                })).then(callback, errorCallback);
            }
        };
    })
    .factory('logger', ['$rootScope', 'ajax', '$location', function ($rootScope, ajax, $location) {
        var loggers = {};
        loggers.actLog = function (action, module, parameter, remark) {
            var inserter = new Req.POST({
                resource: 'log/action',
                fields: {
                    action: action,
                    module: module,
                    parameter: (parameter ? parameter : null),
                    remark: (remark ? remark : null),
                    userId: $rootScope.loginUser.id,
                    userName: $rootScope.loginUser.username
                }
            });
            return ajax.call(inserter);
        };
        loggers.secLog = function (action, module, parameter, remark, rating, status) {
            var len = arguments.length;
            var args = arguments;
            var inserter = new Req.Inserter();
            inserter.fields = {};
            inserter.fields.userId = $rootScope.loginUser.id;
            inserter.fields.userName = $rootScope.loginUser.username;
            inserter.fields.action = args[0];
            inserter.fields.module = args[1];

            if (len == 2) {		// action, module
                inserter.resource = 'log/1/action';
            } else if (len == 3) {	// action, module, rating
                if (typeof args[2] == 'number') {
                    inserter.resource = 'log/' + args[2] + '/action';
                } else {	// action, module, parameter
                    inserter.resource = 'log/1/action';
                    inserter.fields.parameter = args[2];
                }
            } else if (len == 4) {
                if (typeof args[3] == 'number' && args[3] > 0 && args[3] < 5) {	// action, module, parameter, rating
                    inserter.resource = 'log/' + args[3] + '/action';
                    inserter.fields.parameter = args[2];
                } else {	// action, module, parameter, remark
                    inserter.resource = 'log/1/action';
                    inserter.fields.parameter = args[2];
                    inserter.fields.remark = args[3];
                }
            } else if (len == 5) {
                if (typeof args[4] && args[4] > 0 && args[4] < 4) {	// action, module, parameter, rating, status
                    inserter.resource = 'log/' + args[3] + '/' + args[4] + '/action';
                    inserter.fields.parameter = args[2];
                } else {	// action, module, parameter, rating, remark
                    inserter.resource = 'log/' + args[3] + '/action';
                    inserter.fields.parameter = args[2];
                    inserter.fields.remark = args[4];
                }
            } else if (len == 6) {	// action, module, parameter, rating, status, remark
                inserter.resource = 'log/' + args[3] + '/' + args[4] + '/action';
                inserter.fields.parameter = args[2];
                inserter.fields.remark = args[5];
            }

            if (inserter.resource) return ajax.c(inserter);
            return null;
        };
        loggers.usrLog = function (action, module, parameter, remark, user) {
            var inserter = new Req.Inserter({
                resource: 'log/user',
                fields: {
                    action: action,
                    module: module,
                    parameter: (parameter ? parameter : null),
                    remark: (remark ? remark : null),
                    userId: null,
                    userName: null,
                    userType: null,
                    url: $location.url(),
                    userAgent: navigator.userAgent
                }
            });
            if ($rootScope.loginUser) {
                inserter.fields.userId = $rootScope.loginUser.id;
                inserter.fields.userName = $rootScope.loginUser.username;
                inserter.fields.userType = $rootScope.loginUser.userType;
            } else if (user) {
                inserter.fields.userId = user.userId ? user.userId : null;
                inserter.fields.userName = user.userName ? user.userName : null;
                inserter.fields.userType = user.userType ? user.userType : null;
            }

            return ajax.c(inserter);
        };
        return loggers;
    }])
    .service('fileUpload', ['$http', function ($http) {
        this.upload = function (file, uploadUrl, params, successCallback, errorCallback) {
            // $http({
            // 	method: 'POST',
            // 	url: uploadUrl,
            // 	headers: {
            // 		'Content-Type': undefined
            // 	},
            // 	transformRequest: angular.identity,
            // 	// transformRequest: function (data) {
            // 	// 	var formData = new FormData();
            // 	// 	angular.forEach(function (value, key) {
            // 	// 		formData.append(key, value);
            // 	// 	});
            // 	// 	return formData;
            // 	// },
            // 	data: { file: file },
            // 	success: successCallback,
            // 	error: errorCallback
            // });
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: uploadUrl,
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(successCallback).fail(errorCallback);
            // var fd = new FormData();
            // fd.append('file', file);
            // $http.post(uploadUrl, fd, {
            // 	params: null,
            // 	// default transformRequest will try to serialize FormData object, override it with the identity function to leave the data intact
            // 	// transformRequest: angular.identity,
            // 	transformRequest: function (params) {
            // 		var fd = new FormData();
            // 		angular.forEach(params, function(value, key) {
            // 			fd.append(key, value);
            // 		});
            // 		return fd;
            // 	},
            // 	// By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us and fills in the correct boundary.
            // 	// Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request
            // 	// headers: { 'Content-Type': undefined },
            // 	responseType: 'json'
            // }).success(successCallback).error(errorCallback);
        };
    }])
    .factory('authorities', ['$rootScope', function ($rootScope) {
        return {
            hasAuthority: function (authority) {
                if (typeof (authority) === 'string') {
                    authority = authority.trim();
                    return $rootScope.loginUser
                        && $rootScope.loginUser.auths
                        && $rootScope.loginUser.auths.indexOf('AUTH_' + authority) >= 0;
                } else {
                    for (var idx in authority) {
                        var auth = authority[idx];
                        auth = auth.trim();
                        if ($rootScope.loginUser
                            && $rootScope.loginUser.auths
                            && $rootScope.loginUser.auths.indexOf('AUTH_' + auth) >= 0)
                            return true;
                    }
                    return false;
                }
//            	return true;
            },
            hasRole: function (role) {
                role = role.trim();
//                return true;
                return $rootScope.loginUser
                    && $rootScope.loginUser.roles
                    && $rootScope.loginUser.roles.indexOf('ROLE_' + role) >= 0;
            }
        };
    }])
    .factory('clients', function () {
        return {
            isPC: function () {
                var userAgentInfo = navigator.userAgent;
                var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPod");
                var flag = true;
                for (var v = 0; v < Agents.length; v++) {
                    if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
                }
                return flag;
            }
        };
    })
    .factory('uuidGenerator', function () {
        return {
            getUUID: function () {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";

                var uuid = s.join("");
                return uuid;
            }
        };
    })
    .factory('page', function (ajax) {
        return {
            load: function (param, page) {
                if (typeof (param) === "number") {
                    ajax.call(new Req.GET({
                        resource: page.res(param)
                    })).then(page.callback, function () { });
                } else if (typeof (param) === "object") {
                    ajax.call(param).then(page.callback, function () { });
                }
            },
            index: function (scope, page) {
                var thiz = this;
                scope.$on('pageIndex', function (event, p) {
                    scope.bigCurrentPage = p;
                    if (scope.queryMap) {
                        thiz.load(new Req.GET({
                            page_index: p,
                            params: scope.queryMap,
                            resource: page.res(p)
                        }), page);
                        return;
                    }
                    thiz.load(p, page);
                });
            },
        };
    })
    .factory('cos', function () {
        var cos = {};
        return {
            host: function () { return cos.host; },
            img: function () { return cos.img; },
            apk: function () { return cos.apk; },
            init: function (data) { cos = data; }
        };
    });